package com.imageflowpro.image_flow_pro.task;



import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.imageflowpro.image_flow_pro.constant.JwtClaimsConstant;
import com.imageflowpro.image_flow_pro.po.*;
import com.imageflowpro.image_flow_pro.properties.MinioProperties;
import com.imageflowpro.image_flow_pro.service.*;
import com.imageflowpro.image_flow_pro.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


//定时处理订单状态
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private IVerificationCodeService iVerificationCodeService;

    @Autowired
    private IMediaOrderService iMediaOrderService;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IMediaImageService iMediaImageService;

    @Autowired
    private IOrderCommentService iOrderCommentService;

    @Autowired
    private IOrderStatusHistoryService iOrderStatusHistoryService;

    // 处理超时的图片
    @Scheduled(cron = "0 0 */2 * * ? ")//每10秒一次：0/10 * * * * ?  每2小时一次：0 0 */2 * * ?
    @Transactional
    public void processTimeoutImage() {
        log.info("开始处理超时订单的图片，验证码，和超过一天都没有激活的账号,{}", LocalDateTime.now());

        // 删除过期验证码
        List<VerificationCode> verificationCodes = iVerificationCodeService.list();
        List<Long> timeoutCodeIdList = verificationCodes.stream()
                .filter(verificationCode -> LocalDateTime.now().isAfter(verificationCode.getExpireAt()))
                .map(VerificationCode::getId)
                .collect(Collectors.toList());
        if (!timeoutCodeIdList.isEmpty()) {
            iVerificationCodeService.removeByIds(timeoutCodeIdList);
        }

        // 删除过期的图片
        List<MediaImage> mediaImageList = iMediaImageService.lambdaQuery()
                .ne(MediaImage::getVerificationId, -1)
                .list();
        Set<Long> timeoutImageIdList = new HashSet<>();
        if (!mediaImageList.isEmpty()) {
            Set<Long> imageCodeIdList = mediaImageList.stream()
                    .map(MediaImage::getVerificationId)
                    .collect(Collectors.toSet());
            List<VerificationCode> validVerificationCodes = iVerificationCodeService.lambdaQuery()
                                                                .in(VerificationCode::getId, imageCodeIdList)
                                                                .list();
            if (validVerificationCodes.isEmpty()) {
                mediaImageList.forEach(mediaImage -> timeoutImageIdList.add(mediaImage.getId()));
            } else {
                Set<Long> validImageIds = validVerificationCodes.stream()
                        .flatMap(v -> mediaImageList.stream()
                                .filter(m -> m.getVerificationId().equals(v.getId())).map(MediaImage::getId)
                        )
                        .collect(Collectors.toSet());
                timeoutImageIdList.addAll(mediaImageList.stream().map(MediaImage::getId).collect(Collectors.toSet()));
                timeoutImageIdList.removeAll(validImageIds);
            }
        }
        // 删除时间在6个月以上且已经完成或作废的订单
        List<MediaOrder> deleteOrderList = iMediaOrderService.lambdaQuery()
                .le(MediaOrder::getCreatedAt, LocalDateTime.now().minusMonths(6))
                .in(MediaOrder::getCurrentStatus, Arrays.asList(4, 5))
                .list();
        List<OrderStatusHistory> historyList = new ArrayList<>();
        List<Long> deleteOrderIdList = new ArrayList<>();
        //记录更新状态
        if (!deleteOrderList.isEmpty()) {
            deleteOrderList.forEach(mediaOrder -> {
                deleteOrderIdList.add(mediaOrder.getId());
                mediaOrder.setCurrentStatus(5);
                mediaOrder.setIsValid(false);
                if (mediaOrder.getIsValid()) {
                    OrderStatusHistory orderStatusHistory = new OrderStatusHistory();
                    orderStatusHistory.setRemark("订单已经过期，将当前订单设置为无效同时删除图片");
                    orderStatusHistory.setOrderId(mediaOrder.getId());
                    orderStatusHistory.setOldStatus(mediaOrder.getCurrentStatus());
                    orderStatusHistory.setNewStatus(5);
                    orderStatusHistory.setModifiedBy(-1L);
                    historyList.add(orderStatusHistory);
                }
            });
            iMediaOrderService.updateBatchById(deleteOrderList);
            Db.saveBatch(historyList);
            List<MediaImage> deleteOrderMediaImageList = iMediaImageService.lambdaQuery()
                    .in(MediaImage::getOrderId, deleteOrderIdList)
                    .list();
            deleteOrderMediaImageList.forEach(mediaImage -> timeoutImageIdList.add(mediaImage.getId()));
        }
        if (!timeoutImageIdList.isEmpty()) {
            List<MediaImage> deleteImageList = iMediaImageService.lambdaQuery()
                    .in(MediaImage::getId, timeoutImageIdList)
                    .list();
            deleteImageList.forEach(image -> minioUtil.deleteFile(minioProperties.getBucketName(), image.getUploadBy() + "/" + image.getMinioName()));

            iMediaImageService.removeBatchByIds(timeoutImageIdList);
        }


        // 删除超过一天没有激活且没有关联订单的账号
        List<User> userList = iUserService.lambdaQuery()
                .ne(User::getRole, JwtClaimsConstant.USER_ROLE)
                .apply("created_at = updated_at")
                .eq(User::getActive, false)
                .list();
        List<Long> userTimeoutIdList = userList.stream()
                .filter(user -> user.getCreatedAt().plusDays(1).isBefore(LocalDateTime.now()))
                .map(User::getId)
                .collect(Collectors.toList());
        if (!userTimeoutIdList.isEmpty()) {
            List<MediaOrder> userTimeoutOrderList = iMediaOrderService.lambdaQuery()
                    .in(MediaOrder::getUserId, userTimeoutIdList)
                    .list();
            Set<Long> userTimeoutOrderIdList = userTimeoutOrderList.stream().map(MediaOrder::getId).collect(Collectors.toSet());
            userTimeoutIdList.removeAll(userTimeoutOrderIdList);
            if (!userTimeoutIdList.isEmpty()) {
                iUserService.removeBatchByIds(userTimeoutIdList);
            }
        }

        // 删除所有成功一年的订单信息，包括评论，状态记录
        List<MediaOrder> outTimeYearOrderList = iMediaOrderService.lambdaQuery()
                .le(MediaOrder::getCreatedAt, LocalDateTime.now().minusMonths(12))
                .list();
        List<Long> outTimeYearOrderIdList = outTimeYearOrderList.stream().map(MediaOrder::getId).collect(Collectors.toList());
        if (!outTimeYearOrderIdList.isEmpty()) {
            iOrderCommentService.removeBatchByIds(iOrderCommentService.lambdaQuery().in(OrderComment::getOrderId, outTimeYearOrderIdList).list().stream().map(OrderComment::getId).collect(Collectors.toList()));
            iOrderStatusHistoryService.removeBatchByIds(iOrderStatusHistoryService.lambdaQuery().in(OrderStatusHistory::getOrderId, outTimeYearOrderIdList).list().stream().map(OrderStatusHistory::getId).collect(Collectors.toList()));
            iMediaOrderService.removeBatchByIds(outTimeYearOrderIdList);
        }

    }
}